import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, Select, Spin } from 'antd';
import { searchstuList } from '../service'
const { Option } = Select;
const FormItem = Form.Item;

const CreateForm = props => {
  const [classvalue, setclassvalue] = useState('')
  const [classdata, setclassdata] = useState([])
  const [classfetch, setclassfetch] = useState(false)
  const [lastFetchId, setlastFetchId] = useState(0)
  const [types, settypes] = useState(1)
  // 经 Form.useForm() 创建的 form 控制实例，不提供时会自动创建
  const [form] = Form.useForm();
  // 把父组件方法和属性传递过来到子组件
  const { current, modalVisible, onSubmit, onCancel } = props;
  // 点击确定的增加方法，里面调用了父组件的方法 触发表单验证收集value值
  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    console.log(form, fieldsValue)
    // console.log(fieldsValue.type)
    // 利用父组件传递过来的方法，顺便传此子组件的值。进行调用
    onSubmit(fieldsValue);
  };
  // 监听编辑传过来的数据渲染上
  useEffect(() => {
    if (form && !modalVisible) {
      // 每一次刷新都重置一次
      form.resetFields();
    }
    console.log(props, current, form, props.current)
  }, [props.modalVisible]);
  useEffect(() => {
    // 如果有props.current的值才会执行这个
    if (current) {
      settypes(current.type)
      form.setFieldsValue({
        ...current,
        // createdAt: current.createdAt ? moment(current.createdAt) : null,
      });
      setclassvalue(current.class_code)
            fetchUser(current.class_code)

      console.log(current, form.getFieldValue())
    }
  }, [props.current]);
  const fetchUser = async value => {
    console.log('fetching user', value);
    setlastFetchId(lastFetchId + 1);
    const fetchId = lastFetchId;
    setclassdata([])
    setclassfetch(true)
    const datas = await searchstuList({ name: value })
    if (fetchId !== lastFetchId) {
      // for fetch callback order
      return;
    }
    if (datas) {
      setclassdata(datas.data)
    }


  };

  const handleChange = value => {
    console.log(value)
    form.setFieldsValue({ 'class_id': value })

  };
  const changetype = (val) => {
    settypes(val)
  }

  return (
    // 弹出对话框 destroyOnClose关闭时销毁model子元素 //onok点击确定回调
    <Modal

      destroyOnClose
      title={current ? '人员编辑' : '人员添加'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form form={form} >
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="账号"
          name="username"
          rules={[
            {
              required: true,
              message: '必填信息！',
            },
          ]}
        >
          <Input placeholder="请输入" disabled={current? true : false} />
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="姓名"
          name="name"
          rules={[
            {
              required: true,
              message: '必填信息！',
            },
          ]}
        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="类型"
          name="type"
          rules={[
            {
              required: true,
              message: '必填信息！',
            },
          ]}
          shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}
        >
          <Select placeholder="Please select a option" defaultValue={current ? current.type : ''} onChange={changetype}>
            <Option value={1} >高级教师</Option>
            <Option value={2} >普通教师</Option>
            <Option value={3} >学生</Option>
          </Select>
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="学号/工号"
          name="student_number"
          rules={[
            {
              required: types=='3'? true : false,
              message: '学生需要填写学号',
            },
          ]}
        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem

shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}

        >
          {
              types=='3'? (
              <Form.Item label="班级"
              help='可搜索班级名或者班级编号'
              name="class_id" labelCol={{
                span: 5,
              }}
              wrapperCol={{
                span: 15,
              }} rules={[{ required: true }]}>
                <Select
              showSearch
              defaultValue={current ? current.class_name : ''}
              value={classvalue}
              placeholder="班级名或者班级编号"
              notFoundContent={classfetch ? <Spin size="small" /> : null}
              filterOption={false}
              onSearch={fetchUser}
              onChange={handleChange}
              style={{ width: '100%' }}
            >
              {classdata.map(d => (
                <Option key={d.id} value={d.id}>{d.class_name}</Option>
              ))}
            </Select>

            </Form.Item>
            ) : null
           
            
          }


        </FormItem>
      </Form>
    </Modal>
  );
};

export default CreateForm;
